package com.DosonLeung.homeschoolcommunication.Modules.CameraModule;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.TimeUtil;

import java.io.File;

public class CameraActivity extends Activity {
    private static final String TAG = "CamTestActivity";
    private String filePath;
    Preview preview;
    Camera camera;
    Activity act;
    Context ctx;
    ImageView takePicture;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ctx = this;
        act = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.camera);

        preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
        preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        ((RelativeLayout) findViewById(R.id.camera_layout)).addView(preview);
        takePicture = (ImageView) findViewById(R.id.take_picture_btn);
        preview.setKeepScreenOn(true);
        takePicture.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                camera.takePicture(shutterCallback, rawCallback, jpegCallback);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        int numCams = Camera.getNumberOfCameras();
        if(numCams > 0){
            try{
                camera = Camera.open(0);
                camera.startPreview();
                preview.setCamera(camera);
            } catch (RuntimeException ex){
                Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onPause() {
        if(camera != null) {
            camera.stopPreview();
            preview.setCamera(null);
            camera.release();
            camera = null;
        }
        super.onPause();
    }

    private void resetCam() {
        camera.startPreview();
        preview.setCamera(camera);
    }

    private void refreshGallery(File file) {
        Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(Uri.fromFile(file));
        sendBroadcast(mediaScanIntent);
    }

    ShutterCallback shutterCallback = new ShutterCallback() {
        public void onShutter() {
            //			 Log.d(TAG, "onShutter'd");
        }
    };

    PictureCallback rawCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            //			 Log.d(TAG, "onPictureTaken - raw");
        }
    };

    PictureCallback jpegCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            if (SaveImageTask(data)) {
                Intent intent = getIntent();
                intent.putExtra("camera", filePath);
                CameraActivity.this.setResult(RESULT_OK, intent);
                CameraActivity.this.finish();
            } else {
                Toast.makeText(CameraActivity.this, "保存照片失败", Toast.LENGTH_LONG).show();
                Intent intent = getIntent();
                CameraActivity.this.setResult(RESULT_OK, intent);
                CameraActivity.this.finish();
            }
        }
    };

    private boolean SaveImageTask(byte[]... data){
        String time = TimeUtil.getTime();
        Bundle bundle = getIntent().getExtras();
        String target = bundle.getString("target");
        if(StorageUtil.saveImageInAlbum(target, time, data)) {
            //Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
            refreshGallery(getImageInAlbumByName(target,time));
            filePath = target + time;
            return true;
        }else
            return false;
    }

    public File getImageInAlbumByName(String target,String time){
        String en = Environment.getExternalStorageState();
        if (en.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File file = new File(StorageUtil.getCameraDir(),target+time);
                if(file.exists()){
                    return file;
                }else{
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }
}

